package bradd.tom;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.util.Calendar;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
 
import android.provider.*;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentProvider;
import android.content.ContentProviderClient; 
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Tom extends Activity  {
	
	Databasehelper dbasehelper;
	 private TextView mDateDisplay;
	    private Button mPickDate;
	    private int mYear;
	    private int mMonth;
	    private int mDay;
	    private EditText pname;
	    public Calendar usrcal;
	    public AccountManager manage;
	    public ContentProviderClient cal;
	    
	    String CalId;

	

	    static final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button report = (Button)findViewById(R.id.report);
        report.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent report = new Intent(Tom.this, Report.class);
				Tom.this.startActivity(report);
				
			}
		});
        
        dbasehelper = new Databasehelper(this, 2);
        
        
        
        pname = (EditText)findViewById(R.id.pname);
        
        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        mPickDate = (Button) findViewById(R.id.pickDate);
        
        

        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();

        Button add = (Button)findViewById(R.id.add);
        add.setOnClickListener(new OnClickListener() 
        {
			
			@Override
			public void onClick(View v) {
			
			additem(pname.getText().toString(), mDateDisplay.getText().toString());
			try {
				addtogcal();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			}
		});
        
        Button display = (Button)findViewById(R.id.display);
        display.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				displayproduct();
				
			}
		});
        
        Button scan = (Button)findViewById(R.id.scan);
        scan.setOnClickListener( new View.OnClickListener() {
            public void onClick(View v) {
                Intent mscan = new Intent("com.google.zxing.client.android.SCAN");
                mscan.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");

                startActivityForResult(mscan, 0);
            
        }
  
        });
        
       
        
       
    }
        

        public void onActivityResult (int requestCode, int resultCode, Intent mscan) 
        {
            if (requestCode == 0) 
            {
                if (resultCode == RESULT_OK)
                {
                    String contents = mscan.getStringExtra("SCAN_RESULT");
                    String format = mscan.getStringExtra("SCAN_RESULT_FORMAT");
                   Toast w = Toast.makeText(this, contents , Toast.LENGTH_SHORT);
                   w.show();
                    
                    // Handle successful scan
                } 
                else
                	if (resultCode == RESULT_CANCELED)
                	{
                	Toast v = Toast.makeText(getBaseContext(), "booo", Toast.LENGTH_SHORT);
                	v.show();
                    // Handle cancel
                	}
            }
        }
        
        public void additem(String product_name, String date)
        {
        
        	SQLiteDatabase writedata = dbasehelper.getWritableDatabase();
        	if (writedata.isOpen())
        	{
                ContentValues initialValues = new ContentValues();
                initialValues.put("Product_name", product_name);
                initialValues.put("Exp_Date", date);

        	writedata.insert("inventory", null, initialValues);
        	writedata.close();
        	
        	}
        }
        
        private void updateDisplay() {
            mDateDisplay.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(mYear).append("-")
                        .append(mMonth + 1).append("-")
                        .append(mDay).append(""));
        }
        private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
            
            @Override
            protected Dialog onCreateDialog(int id) {
                switch (id) {
                case DATE_DIALOG_ID:
                    return new DatePickerDialog(this,
                                mDateSetListener,
                                mYear, mMonth, mDay);
                }
                return null;
            }
            
       public void displayproduct()
       
       {
    	SQLiteDatabase read = dbasehelper.getReadableDatabase();
    	Cursor cur = read.query("inventory", new String[]{"Product_name"}, null, null, null, null, null);
    	cur.moveToNext();
    	Toast d = Toast.makeText(this, cur.getString(0), Toast.LENGTH_SHORT);
    	d.show();
    	cur.close();
       }
       
       
   
        


//       public Uri addtocal(int calId) throws RemoteException
//       {
//    	   
//    	   int jYear = mYear-1900;
//    	   int jMonth = mMonth;
//    	   int jDay = mDay;
//    	   int id = 2;
//    	   ContentProviderClient calclient;
//    	   ContentProvider calendar;
//    	   String calName;
//    	   String calId;
//    	   Date ddate = new Date(jYear,jMonth,jDay);
//    	   String[] projection = new String[] { "_id", "name" };
//    	   Uri calendars = Uri.parse("content://com.android.calendar/calendars");
//    	   ContentResolver cr = getContentResolver();
//    	   calclient = cr.acquireContentProviderClient(calendars);  
//    	        
//    	   Cursor managedCursor =
//    	     managedQuery(calendars, projection, null, null, null);
//
//    	   
//    	   if (managedCursor.moveToFirst()) {
//    		   int nameColumn = managedCursor.getColumnIndex("name"); 
//    		   int idColumn = managedCursor.getColumnIndex("_id");
//    		   do {
//    		      calName = managedCursor.getString(nameColumn);
//    		      calId = managedCursor.getString(idColumn);
//    		   } while (managedCursor.moveToNext());
//    		  }
//    	   managedCursor.close();
//
//    	   
//    	   Date startdate = ddate;
//    	   String prodname = pname.getText().toString();
//    	  
//    	   
//
//
//    	   mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
//    	   pname = (EditText)findViewById(R.id.pname);
//    	   ContentValues event = new ContentValues();
//    	   
//    	   event.put("title", "Expiration");
//    	   event.put("calendar_id", 2);
//    	   event.put("description", prodname);
//    	   event.put("eventLocation", "My House");
//    	   String startTime = startdate.toString();
//    	   event.put("dtstart", startTime);
//    	   event.put("dtend", startTime);
//    	   event.put("allDay", 1);
//    	   event.put("eventStatus", 1);
//           event.put("visibility", 0);
//           event.put("transparency", 0);
//           event.put("hasAlarm", 0); 
//    	   
//    	   
//    	   Uri eventsUri = Uri.parse("content://com.android.calendar/events");
//    	   Uri url = getContentResolver().insert(eventsUri, event);
//    	   return url;
//    	   
//
//    	
//    	   
//           
//
//
//    	 
//
//
//
//
//       }
//       
//       
//           ContentValues event = new ContentValues();
//
//           event.put("calendar_id", calId);
//           event.put("title", "Birthday [TEST]");
//           event.put("description", "All Day Event");
//           event.put("eventLocation", "Worldwide");
//
//           long startTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
//
//           event.put("dtstart", startTime);
//           event.put("dtend", startTime);
//
//           event.put("allDay", 1); // 0 for false, 1 for true
//           event.put("eventStatus", 1);
//           event.put("visibility", 0);
//           event.put("transparency", 0);
//           event.put("hasAlarm", 0); // 0 for false, 1 for true
//
//           Uri eventsUri = Uri.parse(getCalendarUriBase()+"events");
//           Uri insertedUri = getContentResolver().insert(eventsUri, event);
//           return insertedUri;
//
//       } 

     
       
       public void addtogcal() throws IOException, ServiceException
       {
    	   
    	   CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
    	   myService.setUserCredentials("jmbradd@gmail.com", "gatorade1");

    	// Send the request and print the response
    	URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
    	CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
    	System.out.println("Your calendars:");
    	System.out.println();
    	for (int i = 0; i < resultFeed.getEntries().size(); i++) {
    	  CalendarEntry entry = resultFeed.getEntries().get(i);
    	  System.out.println("\t" + entry.getTitle().getPlainText());
    	   int jYear = mYear-1900;
    	   int jMonth = mMonth;
    	   int jDay = mDay;
    	   Date ddate = new Date(jYear,jMonth,jDay);
    	   Date startdate = ddate;
    	   String startTimed = startdate.toString();
    	   URL postUrl =
    		   new URL("https://www.google.com/calendar/feeds/jmbradd@gmail.com/private/full");
    		 CalendarEventEntry myEntry = new CalendarEventEntry();
    		 myEntry.setTitle(new PlainTextConstruct("Expiration"));
    		 myEntry.setContent(new PlainTextConstruct("Product"+pname.getText()+"expires today"));
    		 DateTime startTime = DateTime.parseDateTime(startTimed);
    		 DateTime endTime = DateTime.parseDateTime(startTimed);
    		 When eventTimes = new When();
    		 eventTimes.setStartTime(startTime);
    		 eventTimes.setEndTime(endTime);
    		 myEntry.addTime(eventTimes);

    		 // Send the request and receive the response:
    		 CalendarEventEntry insertedEntry = myService.insert(postUrl, myEntry);
       }

   }
}




    
